package com.cy.module;

import com.cy.ext.plugin.route.ControllerBind;
import com.cy.model.Account;
import com.cy.model.AccountMapRole;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang.StringUtils;

@ControllerBind(controllerKey = "/clmp/accountMapRole")
public class AccountMapRoleController extends WebApiController {
    @Override
    public void index() {
        AccountMapRole accountMapRole = getModel(AccountMapRole.class);
        int page = getParaToInt("pageIndex");
        int pageSize = getParaToInt("limit");
        Page<AccountMapRole> accountMapRolePage = AccountMapRole.dao.paginate(page, pageSize, AccountMapRole.SELECT_ALL, accountMapRole);
        renderBuiPage(accountMapRolePage, 200);
    }

    @Override
    public void update() {
        int id = getParaToInt();
        AccountMapRole tempAccountMapRole = getModel(AccountMapRole.class);
        AccountMapRole accountMapRole = AccountMapRole.dao.findById(id);
        accountMapRole.cover(tempAccountMapRole);

        if (accountMapRole.update()) {
            renderSuccess();
        } else {
            renderFail();
        }
    }

    @Override
    public void save() {
        String acc = getPara("account");
        if (StringUtils.isBlank(acc)){
            renderFail("账号为空");
            return;
        }
        Account account = Account.dao.getByAccount(acc);
        if (account == null){
            renderFail("账号不存在");
            return;
        }

        AccountMapRole accountMapRole = getModel(AccountMapRole.class);
        accountMapRole.setAccountId(account.getAccountId());
        try {
            accountMapRole.save();
            renderSuccess();
        } catch (Exception e){
            e.printStackTrace();
            renderFail();
        }
    }

    @Override
    public void delete() {
        String[] ids = getPara().split("-");
        for (String id : ids) {
            AccountMapRole.dao.deleteById(id);
        }
        renderSuccess();
    }
}
